<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="false" v-show="showSearch" label-width="85px">
      <el-row>
        <el-col :span="5">
          <el-form-item label="客户名称" prop="customer">
            <el-input
              v-model="queryParams.customer"
              placeholder="请输入客户名称"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>

        <el-col :span="5">
          <el-form-item label="发票状态" prop="state">
            <el-select v-model="queryParams.state" placeholder="请选择发票状态" clearable size="small">
              <el-option
                v-for="dict in stateOptions.invoiceState"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="收款状态" prop="collectionState">
            <el-select v-model="queryParams.collectionState" placeholder="请选择收款状态" clearable size="small">
              <el-option
                v-for="dict in stateOptions.collectionState"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="开票日期" prop="invoiceDate">
            <el-date-picker clearable size="small"
                            v-model="queryParams.invoiceDate"
                            type="date"
                            value-format="yyyy-MM-dd"
                            placeholder="选择收款日期">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="开票人" prop="invoiceUser">
            <el-input
              v-model="queryParams.invoiceUser"
              placeholder="请输入开票人"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
      </el-row>

<!--      <el-form-item label="发票编号" prop="code" v-if="false">-->
<!--        <el-input-->
<!--          v-model="queryParams.code"-->
<!--          placeholder="请输入发票编号"-->
<!--          clearable-->
<!--          size="small"-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->




      <el-form-item label="税率" prop="taxRate" v-if="false">
        <el-input
          v-model="queryParams.taxRate"
          placeholder="请输入税率"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="税额" prop="taxAmount" v-if="false">
        <el-input
          v-model="queryParams.taxAmount"
          placeholder="请输入税额"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="发票金额" prop="invoiceAmount" v-if="false">
        <el-input
          v-model="queryParams.invoiceAmount"
          placeholder="请输入发票金额"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-row>
        <el-col :span="5">
          <el-form-item label="合同编码" prop="contractId">
            <el-input
              v-model="queryParams.contractCode"
              placeholder="请选择合同"
              prefix-icon="el-icon-search"
              size="small"
              readonly
              @click.native="showContractSelect"
            />
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="合同标题" prop="contractId">
            <el-input
              v-model="queryParams.contractName"
              placeholder="请选择合同"
              clearable
              size="small"
             readonly
            />
          </el-form-item>
        </el-col>
        <el-col :span="4">
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          :disabled="queryParams.contractId==null"
          @click="handleAdd"
          v-hasPermi="['contract:invoice:add']"
        >新增开票</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          aria-readonly="true"
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          :disabled="queryParams.contractId!=null"
          @click="handleAdd"
          v-hasPermi="['contract:invoice:add']"
        >无合同开票</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          :disabled="currentRow==null||currentRow.state!=0"
          plain
          icon="el-icon-check"
          size="mini"
          @click="handleApprove"
          v-hasPermi="['contract:main:approve']"
        >确认</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['contract:invoice:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="invoiceList" @row-click="handleRowClick" highlight-current-row>
      <el-table-column label="发票编号" align="center" prop="code" />
      <el-table-column label="客户名称" align="center" prop="customer" />
      <el-table-column label="合同" align="center" prop="contractId" v-if="false"/>
      <el-table-column label="收款状态" align="center" prop="collectionState" width="95px" :formatter="collectionStateFormat"/>
      <el-table-column label="已收款金额" align="center" prop="receivedAmount" width="115px"><template slot-scope="scope">{{scope.row.receivedAmount}}元</template></el-table-column>
      <el-table-column label="发票状态" align="center" prop="state" :formatter="invoiceStateFormat" />
      <el-table-column label="发票金额" align="center" prop="invoiceAmount" ><template slot-scope="scope">{{scope.row.invoiceAmount}}元</template></el-table-column>
      <el-table-column label="税率" align="center" prop="taxRate" ><template slot-scope="scope">{{scope.row.taxRate}}%</template></el-table-column>
      <el-table-column label="税额" align="center" prop="taxAmount" ><template slot-scope="scope">{{scope.row.taxAmount}}元</template></el-table-column>
      <el-table-column label="开票日期" align="center" prop="invoiceDate" />
      <el-table-column label="开票人" align="center" prop="invoiceUser" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.state==0"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['contract:invoice:edit']"
          >修改</el-button>
          <el-button
            v-if="scope.row.state==0"
            size="mini"
            type="danger"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['contract:invoice:remove']"
          >删除</el-button>
          <el-button
            v-if="scope.row.state!=0&&scope.row.collectionState<8"
            size="mini"
            type="text"
            icon="el-icon-link"
            @click="routeRedirect('/contract/collection',{invoiceId:scope.row.gid})"
            v-hasPermi="['contract:invoice:collection']"
          >收款</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-upload"
            @click="routeRedirect('/tool/attachment',{belongId:scope.row.gid})"
            v-hasPermi="['contract:invoice:attachment']"
          >附件</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改发票管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1350px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="发票编号" prop="code">
              <el-input v-model="form.code" placeholder="请输入发票编号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客户名称" prop="customer">
              <el-input v-model="form.customer" placeholder="请输入客户名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="合同编码" prop="contractId">
              <el-input
                v-model="form.contractCode"
                size="small"
                readonly
              />
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="合同标题" prop="contractId">
              <el-input
                v-model="form.contractName"
                clearable
                size="small"
                readonly
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="发票金额" prop="invoiceAmount">
              <el-input v-model="form.invoiceAmount" placeholder="请输入发票金额" type="Number"><template slot="append">元</template></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="税率" prop="taxRate">
              <el-input v-model="form.taxRate" placeholder="请输入税率" type="Number"><template slot="append">%</template></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="税额" prop="taxAmount">
              <el-input :value="form.invoiceAmount*form.taxRate*0.01" placeholder="请输入税额" type="Number" readonly><template slot="append">元</template></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="开票日期" prop="invoiceDate">
              <el-date-picker clearable size="small" v-model="form.invoiceDate" type="date" value-format="yyyy-MM-dd" placeholder="选择开票日期"></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="开票人" prop="invoiceUser">
              <el-input v-model="form.invoiceUser" placeholder="请输入开票人" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="发票状态" prop="state">
              <el-select v-model="form.state" placeholder="请选择发票状态" disabled>
                <el-option
                  v-for="dict in stateOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="parseInt(dict.dictValue)"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="合同ID" prop="contractId" v-if="false">
          <el-input v-model="form.contractId" placeholder="请输入合同ID" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <contract-select ref="cont" :contractOpen="contractOpen" dialogWidth="1350px" @showContractStateSync="showContractStateSync" @selectContract="selectContract"></contract-select>
  </div>
</template>

<script>
import { listInvoice, getInvoice, delInvoice, addInvoice, updateInvoice,approveInvoice, exportInvoice } from "@/api/contract/invoice";
import contractSelect from "@/views/contract/main/select";

export default {
  name: "Invoice",
  components: {
    contractSelect
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      //当前选中行
      currentRow: null,
      // 总条数
      total: 0,
      // 发票管理表格数据
      invoiceList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      //合同选择框显示
      contractOpen:false,
      // 发票状态字典
      stateOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        code: null,
        customer: null,
        contractId: null,
        state: null,
        collectionState: null,
        taxRate: null,
        taxAmount: null,
        invoiceAmount: null,
        invoiceDate: null,
        invoiceUser: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        code: [
          { required: true, message: "发票编号不能为空", trigger: "blur" }
        ],
        customer: [
          {required: true, message: "客户名称不能为空", trigger: "blur" }
        ],
        invoiceAmount: [
          {required: true, message: "发票金额不能为空", trigger: "blur" }
        ],
        taxRate:[
          {required: true, message: "税率不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.queryParams.contractId = this.$route.query.contractId;
    this.getDicts("common_bill_state").then(response => {
      this.stateOptions.invoiceState = response.data;
    });
    this.getDicts("collection_state").then(response => {
      this.stateOptions.collectionState = response.data;
    });
    this.getList();
  },
  methods: {
    /** 查询发票管理列表 */
    getList() {
      this.currentRow = null;
      this.loading = true;
      listInvoice(this.queryParams).then(response => {
        this.invoiceList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    routeRedirect(path,query) {
      this.$router.push({
        path,
        query
      })
    },
    // 发票状态字典翻译
    invoiceStateFormat(row, column) {
      return this.selectDictLabel(this.stateOptions.invoiceState, row.state);
    },
    //发票状态字典翻译
    collectionStateFormat(row, column) {
      return this.selectDictLabel(this.stateOptions.collectionState, row.collectionState);
    },
    //合同选择框
    showContractSelect(){
      this.contractOpen = true;
    },
    selectContract(row){
      this.contractOpen = false;
      if (this.queryParams.contractId==null){
        this.queryParams.contractId = row.gid;
      }
      this.queryParams.contractAmount = row.contractAmount;
      if (this.queryParams.customer == null){
        this.$set(this.queryParams,"customer",row.customer);
      }
      this.$set(this.queryParams,"contractCode",row.code);
      this.$set(this.queryParams,"contractName",row.name);
    },
    // //点击行触发，选中或不选中复选框
    handleRowClick(row) {
      this.currentRow = row;
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    //监测路由变化，刷新页面
    watchRoute(){
      this.queryParams.contractId = this.$route.query.contractId;
      this.getList();
      },
    // 表单重置
    reset() {
      this.form = {
        gid: null,
        code: null,
        customer: null,
        contractId: null,
        state: null,
        taxRate: null,
        taxAmount: null,
        invoiceAmount: null,
        invoiceDate: null,
        invoiceUser: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams={};
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.form.contractId=this.queryParams.contractId;
      const curDate = new Date();
      const month =curDate.getMonth() < 9 ? "0" + (curDate.getMonth() + 1) : curDate.getMonth() + 1;
      const date = curDate.getDate() <= 9 ? "0" + curDate.getDate() : curDate.getDate();
      this.form.invoiceDate = curDate.getFullYear() + "-" + month + "-" + date;
      this.form.state = 0;
      this.form.collectionState = 0;
      this.form.invoiceAmount = this.queryParams.contractAmount;
      this.form.customer = this.queryParams.customer;
      this.form.contractCode=this.queryParams.contractCode;
      this.form.contractName=this.queryParams.contractName;
      this.open = true;
      this.title = "添加发票管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const gid = row.gid || this.currentRow.gid
      getInvoice(gid).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改发票管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.gid != null) {
            updateInvoice(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addInvoice(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    showContractStateSync(val){
      this.contractOpen = val
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const gid = row.gid||this.currentRow.gid;
      this.$confirm('是否确认删除发票管理编号为"' + row.code + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delInvoice(gid);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有发票管理数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        return exportInvoice(queryParams);
      }).then(response => {
        this.download(response.msg);
      })
    },
    //确认按钮操作
    handleApprove(row){
      const gid = row.gid||this.currentRow.gid;
      approveInvoice(gid).then(response => {
        this.msgSuccess("确认成功");
        this.open = false;
        this.getList();
      });
    },
    //监听关联合同ID改变
    contractIdChange(val){
      if (val==null){
        return;
      }
      const gid = val;
      this.$refs.cont.getRowByGid(gid);
    }
  },
  watch:{
    "$route":"watchRoute",
    'queryParams.contractId':"contractIdChange"
  }
};
</script>

